package com.example.springbootvuetest.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.springbootvuetest.Utils.TokenUtils;
import com.example.springbootvuetest.base.ResultCode;
import com.example.springbootvuetest.entity.*;
import com.example.springbootvuetest.entity.dto.*;
import com.example.springbootvuetest.entity.dto.AdminDto;
import com.example.springbootvuetest.mapper.IdleItemMapper;
import com.example.springbootvuetest.mapper.OrderMapper;
import com.example.springbootvuetest.service.IIdleItemService;
import com.example.springbootvuetest.service.IOrderService;
import com.example.springbootvuetest.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootvuetest.base.Result;
import lombok.RequiredArgsConstructor;
import com.example.springbootvuetest.entity.Admin;
import com.example.springbootvuetest.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;


/**
 * <p>
 * controller
 * </p>
 *
 * @author shuoye
 * @since 2023-03-14
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Api(tags = "REST - ")
@RestController
@RequestMapping("admin")
public class AdminController {
    private final IAdminService adminService;
    private final UserService userService;
    private final IIdleItemService idleItemService;
    private final IOrderService orderService;
    private final OrderMapper orderMapper;

    @GetMapping("/login")
    public Result<AdminDto> login(
            @RequestParam(name = "accountNumber") String accountNumber,
            @RequestParam(name = "adminPassword") String adminPassword
    ) {
        if (StrUtil.isBlank(accountNumber) || StrUtil.isBlank(adminPassword))
            return Result.error("参数错误");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        queryWrapper.eq("admin_password", adminPassword).eq("account_number", accountNumber);
        Admin one = adminService.getOne(queryWrapper);
        if (null == one) {
            return Result.error();
        }
        String token = TokenUtils.getToken(String.valueOf(one.getId()), adminPassword, "admin");
        AdminDto adminDto = new AdminDto();
        BeanUtil.copyProperties(one, adminDto, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        adminDto.setToken(token);
        return Result.success(adminDto);
    }

    @GetMapping("/userList")
    @ApiOperation(value = "分页查询")
    public Result<Map<String, Object>> queryPage(@RequestParam(name = "pageNum") Integer pageNum,
                                                 @RequestParam(name = "pageSize") Integer pageSize,
                                                 @RequestParam(name = "nickname", defaultValue = "") String nickname,
                                                 @RequestParam(name = "status") Integer status
    ) {
        HashMap<String, Object> map = new HashMap<>();
        IPage<User> ipage = new Page<User>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_status", status);
        if (!nickname.equals(""))
            queryWrapper.like("nickname", nickname);
        IPage<User> iPage = userService.page(ipage, queryWrapper.orderByAsc("id"));
        map.put("data", iPage.getRecords());
        map.put("total", iPage.getTotal());
        return Result.success(map);
    }

    @PostMapping("/userUpdate")
    public Result update(@RequestBody User user) {
        boolean flag = userService.updateById(user);
        return flag ? Result.success() : Result.error();
    }

    @DeleteMapping("/userDeleteById/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {
        boolean i = userService.removeById(id);
        return i ? Result.success() : Result.error();
    }

    @PostMapping("/userDeleteBatch")
    public Result delete(@RequestBody List<Integer> ids) {
        boolean i = userService.removeByIds(ids);
        return i ? Result.success() : Result.error();
    }

    @PostMapping("/userSave")
    public Result save(@RequestBody User user) {
        user.setAvatar("http://localhost:8080/image?imageName=file16469605582781002123.jpg");
        user.setUserPassword(RandomUtil.randomNumbers(6));
        boolean c = userService.save(user);
        return c ? Result.success() : Result.error();
    }

    @GetMapping("/updateUserStatus")
    public Result updateUserStatus(@RequestParam("id") Integer id,
                                   @RequestParam("status") Integer status) {
        boolean update = userService.updateUserStatusById(id, status);
        return update ? Result.success() : Result.error();
    }

    @GetMapping("/export-user")
    public void exportUserExcel(HttpServletResponse response, @RequestParam("status") Integer status) throws IOException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_status", status);
        // 从数据库查询出所有的数据
        List<User> list = userService.list(queryWrapper);
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
//        在controller层中的二进制流文件下载方法下配置放行属性：
        response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    public void importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<User> list = reader.readAll(User.class);
        userService.saveBatch(list);
    }

    @PostMapping("/adminAdd")
    @ApiOperation(value = "新增")
    public Result createOne(@RequestBody Admin entity) {
        boolean flag = adminService.save(entity);
        return flag ? Result.success() : Result.error();
    }

    @GetMapping("/adminList")
    @ApiOperation(value = "管理员信息查询")
    public Result<Map<String, Object>> queryAdmin(@RequestParam(name = "pageNum") Integer pageNum,
                                                  @RequestParam(name = "pageSize") Integer pageSize
    ) {
        HashMap<String, Object> map = new HashMap<>();
        IPage<Admin> ipage = new Page<Admin>(pageNum, pageSize);
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        IPage<Admin> iPage = adminService.page(ipage, queryWrapper.orderByAsc("id"));
        map.put("data", iPage.getRecords());
        map.put("total", iPage.getTotal());
        return Result.success(map);
    }

    @GetMapping("/idleList")
    public Result queryIdle(@RequestParam(name = "pageNum") Integer pageNum,
                            @RequestParam(name = "pageSize") Integer pageSize,
                            @RequestParam(name = "idleName", defaultValue = "") String idleName,
                            @RequestParam(name = "status") Integer status) {

        Map<String, Object> adminIdleList = idleItemService.getAdminIdleList(pageNum, pageSize, idleName, status);
        return Result.success(adminIdleList);
    }

    @GetMapping("/updateIdleStatus")
    public Result updateItemStatus(@RequestParam("id") Integer id,
                                   @RequestParam("status") Integer status) {
        boolean update = idleItemService.updateIdleStatus(id, status.byteValue());
        return update ? Result.success() : Result.error();
    }

    @GetMapping("/export-item")
    public void exportItemExcel(HttpServletResponse response, @RequestParam("status") Integer status) throws IOException {
        QueryWrapper<IdleItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("idle_status", status);
        List<IdleItem> list = idleItemService.list(queryWrapper);
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("物品信息", "UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    @GetMapping("/orderList")
    public Result getOrderList(@RequestParam(name = "pageNum") Integer pageNum,
                               @RequestParam(name = "pageSize") Integer pageSize,
                               @RequestParam(name = "orderNumber", defaultValue = "") String orderNumber) {
        Map<String, Object> resMap = orderService.getAllOrder(pageNum, pageSize);
        return Result.success(resMap);
    }

    @GetMapping("/tableData")
    public Result getTableData() {
        List<TableDto> tableOrder = adminService.getTableOrder();
        return Result.success(tableOrder);
    }

    @GetMapping("/yearData")
    public Result getYearData() {
        List<YearData> tableOrder = orderMapper.getYearData();
        return Result.success(tableOrder);
    }

    @GetMapping("/totalTrade")
    public Result getTotalTrade() {
        List<Quarter> sum = orderMapper.getQuarter();
        return Result.success(sum);
    }

    @DeleteMapping("/deleteOrder/orderNumber")
    public Result deleteOrder(@PathVariable("orderNumber") Integer orderNumber) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
        queryWrapper.eq("order_number", queryWrapper);
        boolean b = orderService.remove(queryWrapper);
        return b ? Result.success() : Result.error();
    }

    @PostMapping("/deleteOrderBatch")
    public Result deleteOrder(@RequestBody List<Integer> ids) {
        boolean i = orderService.removeBatchByIds(ids);
        return i ? Result.success() : Result.error();
    }

    @GetMapping("/export-order")
    public void exportOrderExcel(HttpServletResponse response) throws IOException {
        List<Order> list = orderService.exportOrder();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("订单信息", "UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }
}